﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using TCS.DBUtility;
using TCS.Model.Weibo;
using System.Xml;
using LTP.Common;
using WeiBo.SinaAPI;
using LeoShi.Soft.OpenSinaAPI;

namespace TCS.Web.MembersHome
{
    public partial class ActivityMonitor : System.Web.UI.Page
    {
        protected string profile_image_url;
        protected string weibo_userId;
        protected string screen_name;
        protected string created_at;
        protected string source;
        protected string text;
        protected string rtCount;  //转发总数
        protected string commentCount; //评论总数
        protected string fanCount;//粉丝总数
        protected List<Status> statusRecord;//记录
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
               
            }
        }
        //查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (this.txtwbUrl.Text.Trim()=="")
            {
                return;
            }
            ViewState["OrgUrl"] = this.txtwbUrl.Text.Trim();
            GetWbDetail();
            GetRecord();
            GetStatusCount();
        }
        /// <summary>
        /// 得到一条的转发记录
        /// </summary>
        private void GetRecord()
        {
           var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;

            string url = "http://api.t.sina.com.cn/statuses/repost_timeline.json?id=" + getId(ViewState["OrgUrl"].ToString());
            string result = httpRequest.Request(url,string.Empty);
           
             statusRecord = JSONConvert.DeserializeJsonToListObjectStatus(result);
            rptRecord.DataSource = statusRecord;
            rptRecord.DataBind();
            this.lblRecordCount.Text = statusRecord.Count.ToString();

        }
        /// <summary>
        /// 处理原创地址得到微博id
        /// </summary>
        /// <param name="url">原创微博地址</param>
        /// <returns>id</returns>
        private string getId(string url)
        {
            url = url.Trim().Substring(url.LastIndexOf("/") + 1);//
            string newUrl = "http://api.t.sina.com.cn/queryid.json?mid="+url+"&isBase62=1&type=1";
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            string result = httpRequest.Request(newUrl,string.Empty);
            if (!result.Contains('['))
            {
                result = "[" + result + "]";
            }
            List<Queryid> listId = JSONConvert.DeserializeJsonToListSinaId(result);
            string id = "";
            foreach (Queryid queryid in listId)
            {
               id= queryid.id;
                break;
            }
            return id;
        }


        /// <summary>
        /// 得到需要统计的微博的详细信息
        /// </summary>
        private void GetWbDetail()
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            string url = "http://api.t.sina.com.cn/statuses/show/:id.json?id=" + getId(ViewState["OrgUrl"].ToString());
            string result = httpRequest.Request(url, string.Empty);  //DeserializeToStatus
            if(!result.Contains('['))
            {
              result = "[" + result + "]";
            }
            List<Status> detail = JSONConvert.DeserializeJsonToListObjectStatus(result);
            foreach(Status status in detail)
            {
               screen_name=status.user.screen_name;
               profile_image_url = status.user.profile_image_url;
               weibo_userId = status.user.id;
               created_at = SinaDateConvert(status.created_at);
               source = status.source;
               text = status.text;
            }
            rptWeiboDetial.DataSource = detail;
            rptWeiboDetial.DataBind();
        }
        //得到一条微博的评论数和转发数
        private void GetStatusCount()
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            string url = "http://api.t.sina.com.cn/statuses/counts.json?ids=" + getId(ViewState["OrgUrl"].ToString());
            string result = httpRequest.Request(url, string.Empty);
            List<StatusCount> statusCount = JSONConvert.DeserializeJsonToListObjectStatusCount(result);
            foreach(StatusCount rtAndComment in statusCount)
            {
                rtCount = rtAndComment.rt;
                commentCount = rtAndComment.comments;
            }
 
        }
      
        public string SinaDateConvert(object obj)
        {
             string result = DateTime.Now.ToString();
             result=StringHelper.SinaDataConvert(obj.ToString());
             return result;
        }
        /// <summary>
        /// 到处excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImportExcel_Click(object sender, EventArgs e)
        {
            rptImport();
            //DataSet ds = ConvertToDataSet(statusRecord);
            //CreateExcel(ds, "activity.xls");

        } 
        
        public void CreateExcel(DataSet ds, string FileName)
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";

            //定义表对象与行对象，同时用DataSet对其值进行初始化 
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id int i=0; 
            int cl = dt.Columns.Count;


            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            for (int i = 0; i > cl; i++)
            {
                if (i == (cl - 1))//最后一列，加\n
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息 

            //逐行处理数据 
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据 
                for (int i = 0; i > cl; i++)
                {
                    if (i == (cl - 1))//最后一列，加\n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }

                }
                resp.Write(ls_item);
                ls_item = "";

            }
            resp.End();
        }

     //// <summary>
    /// Ilist<T> 转换成 DataSet
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
        public static DataSet ConvertToDataSet(List<Status> list)
    {
        if (list == null || list.Count <= 0)
        {
            return null;
        }

        DataSet ds = new DataSet();
        DataTable dt = new DataTable(typeof(Status).Name);
        DataColumn column;
        DataRow row;

        System.Reflection.PropertyInfo[] myPropertyInfo = typeof(Status).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

        foreach (Status t in list)
        {
            if (t == null)
            {
                continue;
            }

            row = dt.NewRow();

            for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
            {
                System.Reflection.PropertyInfo pi = myPropertyInfo[i];

                string name = pi.Name;

                if (dt.Columns[name] == null)
                {
                    column = new DataColumn(name, pi.PropertyType);
                    dt.Columns.Add(column);
                }

                row[name] = pi.GetValue(t, null);
            }

            dt.Rows.Add(row);
        }

        ds.Tables.Add(dt);

        return ds;
    }
        /// 返回>1则存在重复的字符串，并返回值，如果小于等于1则不存在重复的字符串返回
        /// 查找某一字符串 在目标字符串里出现的次数   思想：首先把目标字符串赋给一个字符串，然后把赋值后的字符串 
        /// 把源目标字符串替换成空值，这样把源字符串的总长度减去赋值后的字符后的总长度便是目标字符串的倍数，
        /// 如果小于等于1，则不存在，如果>1则存在
        /// </summary>
        /// <param name="Enstr">源字符串</param>
        /// <param name="Destr">目标字符串</param>
        /// <returns></returns>
        public static int StringFindStringCount(string Enstr, string Destr)
        {
            int result = 0;

            if (Enstr == null || Enstr.ToString().Trim().Replace("'", "") == "")//当源字符串为空时
            {
                result = 0;
            }
            else
            {
                if (Destr == null || Destr.ToString().Trim().Replace("'", "") == "")//当目标字符串为空时
                {
                    result = 0;
                }
                else
                {
                    if (Enstr.Length < Destr.Length)//当源字符串长度小于目标字符串长度时
                    {
                        result = 0;
                    }
                    else
                    {
                        string str = Enstr;

                        str = str.Replace(Destr, "");

                        int count = (Enstr.Length - str.Length);

                        if (count > 0)
                        {
                            result = count / Destr.Length;//如果此值大于1，则说明存在重复字符串，否则不存在重复的字符串
                        }
                        else
                        {
                            result = 0;
                        }
                    }
                }
            }

            return result;
        }
        //数据处理
        protected void rptRecord_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
               Label content=((Label)e.Item.FindControl("lblText"));
               Label count = ((Label)e.Item.FindControl("lblCount"));
                string Destr="//@";
               int num=StringFindStringCount(content.Text.ToString(),Destr);

               count.Text = num.ToString();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rptImport()
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "utf-8";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("活动监测", System.Text.Encoding.UTF8) + ".xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");     //设置输出流为简体中文
            Response.ContentType = "application/ms-excel";    //设置输出文件类型为excel文件。 
            this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            //   repeater控件的ID
            rptRecord.RenderControl(oHtmlTextWriter);
            Response.Write(oStringWriter.ToString());
            Response.End();
        }

    }
}
